// 与数据库打交道
const {
  create,
  del,
  list,
  count,
  get,
  modules,
  levels,
} = require('../../../model/log')

const { Success, SysErr } = require('../../../response/code')

class LogService {
  async create(ctx) {
    try {
      const data = ctx.request.body
      data.owner_id = ctx.state.owner_id
      data.body = JSON.parse(data.body)
      const result = await create(data)
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async get(ctx) {
    try {
      const query = ctx.request.query
      const result = await get(query.id)
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async del(ctx) {
    try {
      const body = ctx.request.body

      // 存在则删除
      const result = await del(body.id, {
        deleted_at: null,
      })
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async modules(ctx) {
    try {
      const query = ctx.request.query
      const owner_id = query.owner_id
      const result = await modules(owner_id)
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async levels(ctx) {
    try {
      const query = ctx.request.query
      const owner_id = query.owner_id
      const module = query.module
      const result = await levels(owner_id, module)
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async systems(ctx) {
    try {
      const query = ctx.request.query
      const result = await systems()
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }

  async list(ctx) {
    try {
      const query = ctx.request.query
      const where = {
        deleted_at: null,
      }
      if (query.owner_id) {
        where.owner_id = parseInt(query.owner_id)
      }
      if (query.module) {
        where.module = query.module
      }
      if (query.level) {
        where.level = query.level
      }
      if (query.startTime && query.endTime) {
        where.created_at = {
          gte: new Date(query.startTime),
          lte: new Date(query.endTime),
        }
      }

      const data = await list(query.pageNo, query.pageSize, where) // 可以添加第三个参数条件过滤
      const total = await count(where)
      const result = {
        list: data,
        count: total,
      }
      ctx.body = new Success(result).toString()
    } catch (err) {
      return ctx.app.emit('error', new SysErr(err.message, err.stack), ctx)
    }
  }
}
module.exports = new LogService()
